package cn.liyunqi.findimg.task;

import cn.liyunqi.findimg.controller.ProgressBarViewController;
import cn.liyunqi.findimg.controller.WindowCloseHandler;
import javafx.concurrent.Task;

public abstract class ProgressBarViewTask extends Task implements WindowCloseHandler {

    protected ProgressBarViewController progressBarViewController;

    protected ProgressBarViewTaskCallback progressBarViewTaskCallback;

    public void setProgressBarViewController(ProgressBarViewController progressBarViewController) {
        this.progressBarViewController = progressBarViewController;
    }

    public void setProgressBarViewTaskCallback(ProgressBarViewTaskCallback progressBarViewTaskCallback) {
        this.progressBarViewTaskCallback = progressBarViewTaskCallback;
    }

    @Override
    protected Object call() throws Exception {

        try {
            this.doTask();
            if(progressBarViewTaskCallback != null){
                progressBarViewTaskCallback.complete();
            }

        }catch (Exception ex){
            ex.printStackTrace();
            if(progressBarViewTaskCallback != null){
                progressBarViewTaskCallback.error(ex);
            }
        }finally {

        }
        return true;
    }

    abstract void doTask() throws Exception;



    protected void updateProgress(String msg,double workDone, double max){
        if(progressBarViewController != null){
            this.progressBarViewController.updateProgress(msg,workDone,max);
        }
        updateProgress(workDone,max);
    }

    protected void updateMsg(String msg){
        this.progressBarViewController.updateMsg(msg);
    }
}
